package d0517_集合;

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.*;
import java.util.Map.Entry;

public class 记事本 {
	
	// 存放数据的集合, 使用时间作为键,
	private Properties prop = new Properties();
	
	public 记事本() throws IOException {
		try {
			prop.load(new FileInputStream("d:/a.properties"));
		} catch (FileNotFoundException e) {
			// 忽略 文件不存在 
		}
	}
			
	/**
	 * 保存数据
	 * @throws IOException 
	 * @throws FileNotFoundException 
	 */
	public void save(String content) throws FileNotFoundException, IOException {
		String key = "" + new Date().getTime();
		prop.setProperty(key, content);
		/**
		 * new FileOutputStream("d:/a.properties")
		 * 如果 上面的字节流有报错,请使用下面的字符流
		 * prop.store(new FileWriter("d:/a.properties"), "save data");
		 */
		prop.store(new FileOutputStream("d:/a.properties"), "save data");
	}
	
	/**
	 * 显示
	 */
	public void show() {
		TreeMap<Date, String> map = new TreeMap<>();
		Set<Entry<Object, Object>> entrySet = prop.entrySet();
		for(Entry<Object, Object> entry : entrySet) {
			//键    时间戳字符串
			String key = (String)entry.getKey();
			//值     内容
			String content = (String)entry.getValue();
			// 将字符串转成日期类型
			Date date = new Date(Long.parseLong(key));
			map.put(date, content);
		}
		// 将 Properties 转成了 TreeMap  ==> 自动排序
		Set<Entry<Date, String>> entrySet1 = map.entrySet();
		for(Entry<Date, String> entry : entrySet1) {
			System.out.println(entry.getKey()+ ":");
			System.out.println("\t" + entry.getValue());
		}
	}
	
	public static void main(String[] args) throws FileNotFoundException, IOException {
		记事本 a = new 记事本();
		if(args.length>0) {
			a.save(args[0]);
		}
		a.show();
	}
	
}

